package com.example.demo.mq.consumer;

import com.example.demo.mq.bo.ScoreMqBo;
import com.example.demo.mq.config.MqConstant;
import com.rabbitmq.client.Channel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

@AllArgsConstructor
@Component
@Slf4j
public class ScoreMonitorConsumer {

    @RabbitListener(queues = MqConstant.SCORE_QUEUE)
    @RabbitHandler
    public void process(@Payload ScoreMqBo scoreMqBo, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
        try {
            log.info(".....mq 收到消息={}", scoreMqBo);
            //采用手动应答模式，手动确认应答更为安全稳定
            channel.basicAck(tag, true);
        } catch (Exception e) {
            //处理失败
            try {
                channel.basicAck(tag, false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

}
